﻿using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using ImbedLibrary;

namespace ImbedLibrary
{
    public class UserConfig
    {

        /// <summary>
        /// 删除系统(域)用户
        /// </summary>
        /// <param name="strUserName">用户名</param>
        /// <returns></returns>
        public static bool DeleteUser(string strUserName)
        {
            try
            {
                DirectoryEntry oLocalMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
                DirectoryEntry User = oLocalMachine.Children.Find(strUserName, "user");//找到要删除的用户
                if (User.Name != null)
                {
                    oLocalMachine.Children.Remove(User);
                }
                oLocalMachine.Close();
            }
            catch
            {
                throw;
            }
            return true;
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="userPassword">用户密码</param>
        /// <param name="miaoshu">描述</param>
        /// <returns></returns>
        public static string CreateLocalUserAccount(string userName, string userPassword, string miaoshu)
        {
            string returnMsg = "ok";//返回消息
            DirectoryEntry oLocalMachine = null;
            DirectoryEntry oNewUser = null;
            try
            {
                oLocalMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
                oNewUser = oLocalMachine.Children.Find(userName, "user");//创建用户
            }
            catch (Exception)
            {
            }
            try
            {
                if (oNewUser == null)
                {
                    oNewUser = oLocalMachine.Children.Add(userName, "user");//添加用户配置


                    oNewUser.Invoke("SetPassword", new object[] { userPassword });//设置密码
                    oNewUser.CommitChanges();

                    oNewUser.Invoke("Put", new object[] { "Description", miaoshu });//用户描述
                    oNewUser.Invoke("Put", new object[] { "UserFlags", 0x0040 | 66049 });//用户不能更改密码,密码永不过期
                    oNewUser.CommitChanges();

                    oLocalMachine.Close();
                    oNewUser.Close();
                    Logs.Note("创建用户: " + userName);
                }
                else
                {
                    returnMsg = string.Format("用户[{0}],已存在，无法重复创建该用户", userName);
                    Logs.Note("用户存在: " + userName);
                }
            }
            catch (Exception)
            {
            }
            return returnMsg;
        }

    }
}
